#include "registerdialog.h"
#include "ui_registerdialog.h"
#include <textinput.h>
#include <QIcon>
#include <QComboBox>
#include <QDebug>
#include <QMessageBox>

#include <QStringList>

#include <QTimer>
#include <QPushButton>
#include <QThreadPool>

#include <QJsonObject>
RegisterDialog::RegisterDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::RegisterDialog)
{
    ui->setupUi(this);
    qDebug() << "服务器-主线程ID:" << QCoreApplication::instance()->thread()->currentThreadId();

    /* 窗口标题和图片 */
//    this->setWindowTitle("智慧医疗管理系统");
//    QPixmap pixmap;
//    pixmap.load(":/images/TitleIcon.png");
//    QIcon icon;
//    icon.addPixmap(pixmap);
//    this->setWindowIcon(icon);
    /* 窗口标题和图片 */

    ui->labelTitle->setLabelName("智慧医疗系统注册");
    ui->labelTitle->showLabelName();

    createCombox();
    createTextInput();
    createButton();

    m_client = new TcpClient();

    // 连接信号槽
    connect(m_client, &TcpClient::connected,
            [=]()
    {
        qDebug()<<"链接成功"<<endl;
    });
    connect(m_client, &TcpClient::disconnected,
            [=]()
    {
        qDebug()<<"链接断开"<<endl;
    });
    connect(m_client, &TcpClient::dataReceived,
            [=](const QJsonObject& data)
    {
        qDebug()<<"接受信息"<<data["result"].toString()<<endl;
        handleResults(data["result"].toString() == "success"?true:false);
    });
    connect(m_client, &TcpClient::error,
            [=](const QString& errorMessage)
    {
        qDebug()<<"链接错误"<<errorMessage<<endl;
    });


}

RegisterDialog::~RegisterDialog()
{
    delete ui;
}
void RegisterDialog::initializeInterface()
{
    // 确保在发送数据前已经连接
    if (!m_client->isConnected()) {
        m_client->connectToServer("106.54.213.237", 8080);
    }
    this->exec();
}
void RegisterDialog::createButton()
{
    buttot_1 = new QPushButton();
    buttot_2 = new QPushButton();

    buttot_1->setText("登录");
    buttot_2->setText("注册");

    buttonLayout = new QHBoxLayout(ui->buttonWidget);
    buttonLayout->addStretch();
    buttonLayout->addWidget(buttot_1);
    buttonLayout->addWidget(buttot_2);
    buttonLayout->addStretch();

    connect(buttot_2,&QPushButton::clicked,this,&RegisterDialog::RegisterUser);
    connect(buttot_1,&QPushButton::clicked,
            [=]()
    {
        m_client->disconnectFromServer();
        this->accept();
    });
}

void RegisterDialog::createTextInput()
{
    ui->textInput_1->setLabelName("身份证");
    ui->textInput_1->setPlaceholderText("请输入身份证号");
    ui->textInput_1->setTextInputModel("Normal");
    ui->textInput_1->showTextInput();

    ui->textInput_2->setLabelName("密码");
    ui->textInput_2->setPlaceholderText("请输入密码");
    ui->textInput_2->setTextInputModel("Password");
    ui->textInput_2->showTextInput();
}

void RegisterDialog::createCombox()
{
    // 创建 QComboBox 对象
    comboBox = new QComboBox();
    // 添加选项
    comboBox->addItem("患者");
    comboBox->addItem("医生");
    comboBox->addItem("管理员");
    roleLabel = new QLabel();
    roleLabel->setText("角色选择");
    roleLayout = new QHBoxLayout(ui->role);
    roleLayout->addStretch();
    roleLayout->addWidget(roleLabel);
    roleLayout->addWidget(comboBox);
    roleLayout->addStretch();
}
void RegisterDialog::RegisterUser()
{
    this->role = this->comboBox->currentText();
    this->username = ui->textInput_1->getTextInput();
    this->password = ui->textInput_2->getTextInput();
    if(this->role != "患者")
    {
        QMessageBox::information(this, "警告", "权限不足!无法注册!");
        return;
    }
    if(ui->textInput_1->getTextInput().size() == 0)
    {
        QMessageBox::information(this, "输入内容", "注册失败,请填写正确身份证号");
        return;
    }
    if(ui->textInput_2->getTextInput().size() == 0)
    {
        QMessageBox::information(this, "输入内容", "注册失败,请填写正确密码");
        return;
    }
    if(!isValidIDNumber(username))
    {
        QMessageBox::information(this, "输入内容", "注册失败,请填写正确身份证号");
        return;
    }
    if(!isValidPassword(password) || this->password.size()<8)
    {
        QMessageBox::information(this, "输入内容", "注册失败,请填写正确密码八位以上包含字母数字");
        return;
    }

    // Usage
    QString quires = QString("INSERT INTO tms (tms_gg, tms_user, tms_password) "
                    "VALUES (:tms_gg, :tms_user, :tms_password)");
    QJsonObject jsonObj;
    jsonObj["type"] = "注册";
    jsonObj["tms_user"] = username;
    jsonObj["tms_password"] = password;
    jsonObj["tms_gg"] = role;
    jsonObj["sql"] =quires;
    QJsonDocument doc(jsonObj);
    QByteArray data = doc.toJson();
    qDebug() << "Sending data:" << data; // 调试输出
    m_client->sendData(jsonObj);
}

// 身份证号码正则表达式
bool RegisterDialog::isValidIDNumber(const QString &username)
{
    QRegularExpression regex("^\\d{17}[0-9Xx]$");
    QRegularExpressionMatch match = regex.match(username);
    return match.hasMatch();
}

// 简单密码验证:是否包含数字和字母
bool RegisterDialog::isValidPassword(const QString &password)
{
    bool hasNumber = false;
    bool hasLetter = false;

    for (QChar c : password)
    {
        if (c.isDigit())hasNumber = true;
        else if (c.isLetter())
            hasLetter = true;

        if (hasNumber && hasLetter)
            return true;
    }

    return false;
}
void RegisterDialog::handleResults(const bool& results)
{
    if(results)
    {
        // 注册成功关闭当前窗口
        QMessageBox::information(this, "注册结果", "注册成功");
        // 清空文本框内容
        ui->textInput_1->clear();
        ui->textInput_2->clear();
        // 关闭窗口
        this->close();
    }else
    {
        QMessageBox::information(this, "注册结果", "注册失败");
    }
}

void RegisterDialog::handleError(const QString& errorMessage)
{
    qDebug() << "Database error:" << errorMessage;
    QMessageBox::information(this, "注册结果", "注册失败,该账号已存在");
}
